package com.misty.auth.config;

import com.alibaba.fastjson.JSON;
import com.misty.common.Util.WebUtils;
import com.misty.common.bean.Result;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class MyAuthenticationEnryPoint implements AuthenticationEntryPoint {


    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json");
//        String json_reply = JSON.toJSONString(Result.error(HttpStatus.FORBIDDEN.value(), "认证失败!"));
        String json_reply = JSON.toJSONString(Result.error(HttpStatus.FORBIDDEN.value(), e.getMessage()));
        WebUtils.renderString(httpServletResponse,json_reply);

//        httpServletResponse.getWriter().println(JSONUtil.parse(Result.error(HttpStatus.UNAUTHORIZED.toString(),e.getMessage())));
//        httpServletResponse.getWriter().flush();
    }
}
